package com.salim.leetcode.$25;

import java.util.Stack;

public class ReverseNodesinkGroup {
    public ListNode reverseKGroup(ListNode head, int k) {
        if(head==null){
            return null;
        }
        ListNode dummy = new ListNode(0);
        ListNode current = new ListNode(0);
        dummy.next = current;
        Stack<ListNode> stack = new Stack<>();
        boolean end = false;
        while (head!=null){
            current.next = head;
            for(int i=0;i<k;i++){
                stack.push(head);
                if(head.next!=null){
                    head = head.next;
                }else{
                    end = true;
                    break;
                }
            }

            if(!end){
                for(int i=0;i<k;i++){
                    current.next = stack.pop();
                    current = current.next;
                }
            }else{
                if(stack.size()==k){
                    for(int i=0;i<k;i++){
                        current.next = stack.pop();
                        current = current.next;
                    }
                    current.next = null;
                }
                break;
            }
        }
        return dummy.next.next;
    }

    public static void main(String[] args) {
        ReverseNodesinkGroup reverseNodesinkGroup = new ReverseNodesinkGroup();
        ListNode line1 = new ListNode(1);
        ListNode line2 = new ListNode(2);
        ListNode line3 = new ListNode(3);
        ListNode line4 = new ListNode(4);
        ListNode line5 = new ListNode(5);
        ListNode line6 = new ListNode(6);
        ListNode line7 = new ListNode(7);
        line1.next = line2;
        line2.next = line3;
        line3.next = line4;
        line4.next = line5;
        line5.next = line6;
        line6.next = line7;
        ListNode head = reverseNodesinkGroup.reverseKGroup(line1, 3);
        System.out.println(head.toString());
    }
}



class ListNode {
    int val;
    ListNode next;
    ListNode() {}
    ListNode(int val) { this.val = val; }
    ListNode(int val, ListNode next) { this.val = val; this.next = next; }
    @Override
    public String toString() {
        String str =  " ["+this.val+"]";
        if(this.next!=null){
            str += this.next.toString();
        }
        return str;
    }
}
